import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'
/* 
封装一个函数，确定是否含有登录的返回的地址
*/
function hasUrl(url,next){
  //通过some去查找只有存在即为真
  let result = store.getters.getUser.menus_url.some((item)=>item == url)
  if(result){
    next();
  }else{
    next('/home')
  }
}
Vue.use(VueRouter)
export const indexRouters = [
  {
    path:'/menu',
    component:()=>import('../views/menu/menu'),
    meta:{
      title:'菜单管理'
    },
    beforeEnter:(to,from,next)=>{
      hasUrl('/menu',next)
    }
  },
  {
     path:'/role',
     component:()=>import('../views/role/role'),
     meta:{ 
      title:'角色管理'
     },
     beforeEnter:(to,from,next)=>{
      hasUrl('/role',next)
    }
  },
  {
    path:'/user',
    component:()=>import('../views/user/user'),
    meta:{
      title:'管理员管理'
    },
    beforeEnter:(to,from,next)=>{
      hasUrl('/user',next)
    }
  },
  {
    path:"/cate",
    component:()=>import('../views/cate/user'),
    meta: {
      title: "商品分类管理",
    },
    beforeEnter:(to,from,next)=>{
      hasUrl('/cate',next)
    }
  },
  {
    path:'/specs',
    component:()=>import('../views/specs/specs'),
    meta:{
      title:'商品规格'
    }
  },
  {
    path:'/goods',
    component:()=>import('../views/goods/goods'),
    meta:{
      title:'商品管理'
    }
  },
  {
    path:'/banner',
    component:()=>import('../views/banner/banner'),
    meta:{
      title:'轮播图列表'
    }
  },
  {
    path:'/seck',
    component:()=>import('../views/seck/seck'),
    meta:{
      title:'活动列表'
    }
  },
  {
    path:'/member',
    component:()=>import('../views/member/member'),
    meta:{
       title:'会员列表'
    }
  },
  {
    path:'/map',
    component:()=>import('../views/map/map'),
    meta:{
      title:'地图'
    }
  }
  
  
]
  

const routes = [
  {
    path:'/index',
    component:()=>import('../pages/index'),
    children:[
      {
        path:'/home',
        component:()=>import('../views/home')
      },
     ...indexRouters,
      {
        path:'',
        redirect:'/home'
      }
    ]
  },
  {
    path:'/login',
    component:()=>import('../pages/login')
  },
  {
    path:'*',
    redirect:'/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 全局登录拦截
router.beforeEach((to,from,next)=>{
  // 如果跳的是登录就next
  if(to.path == '/login'){
    next();
    return
  }
  // 如果有登录信息就next
  if(store.getters.getUser){
    next();
    return
  }
  // 以上逻辑都没有就跳登录
  next('/login')
})

export default router
